using Godot;
using System;

public partial class NInventoryPanel : Panel
{
	public static string CUR_SEL_PANEL = "CUR_SEL_PANEL";
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		GuiInput += (@event) => onGUIInput(@event);
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		if (GetTree().GetFirstNodeInGroup(NItem.CUR_SEL_ITEM) is NItem item)
		{
			item.GlobalPosition = GetGlobalMousePosition();
		}
	}

	//能否放置物品
	public virtual bool canPut(NItem item)
	{
		//可以放置任何物品
		return true;
	}

	public NItem Item
	{
		get
		{
			if (GetChildCount() > 0)
			{
				return GetChildOrNull<NItem>(0);
			}
			else
			{
				return null;
			}
		}
	}
	public virtual void onGUIInput(InputEvent @event)
	{
		if (@event is InputEventMouseButton mb)
		{
			if (mb.Pressed && mb.ButtonIndex == MouseButton.Left)
			{
				NItem item = Item;
				NItem selItem = GetTree().GetFirstNodeInGroup(NItem.CUR_SEL_ITEM) as NItem;
				if (selItem == null && item != null)
				{
					//存放在group
					item.AddToGroup(NItem.CUR_SEL_ITEM, true);
					item.ZIndex = 1;
					return;
				}

				//当前有物品要放置
				if (selItem != null)
				{
					//当前面板下没有物品
					if (item == null)
					{							
						selItem.RemoveFromGroup(NItem.CUR_SEL_ITEM);
						if (canPut(selItem))
						{
							//可以放置到新面板
							selItem.Reparent(this);
							selItem.ZIndex = 0;
							selItem.adjustPos();
						}
						else
						{
							//类型不符合，重新回到原来位置
							selItem.ZIndex = 0;
							selItem.adjustPos();
						}
					}
					//当前面板下有物品
					else
					{
						//检查是否类型符合
						if (canPut(selItem))
						{
							//符合类型，可以交换
							//selItem : getParent()->面板 NInventory(发生物品页切换的时候)
							//item : this
							NInventoryPanel oriGroupPanel = GetTree().GetFirstNodeInGroup(NInventoryPanel.CUR_SEL_PANEL) as NInventoryPanel;
							if (oriGroupPanel != null)
							{
								selItem.Reparent(oriGroupPanel);
								oriGroupPanel.RemoveFromGroup(NInventoryPanel.CUR_SEL_PANEL);
							}

							NInventoryPanel selPanel = selItem.GetParentOrNull<NInventoryPanel>();
							selItem.Reparent(this);
							selItem.ZIndex = 0;
							selItem.adjustPos();

							item.Reparent(selPanel);
							item.ZIndex = 0;
							item.adjustPos();

							selItem.RemoveFromGroup(NItem.CUR_SEL_ITEM);
						}
						//类型不符合，回到原来面板
						else
						{
							NInventoryPanel oriGroupPanel = GetTree().GetFirstNodeInGroup(NInventoryPanel.CUR_SEL_PANEL) as NInventoryPanel;
							if (oriGroupPanel != null)
							{
								selItem.Reparent(oriGroupPanel);
								oriGroupPanel.RemoveFromGroup(NInventoryPanel.CUR_SEL_PANEL);
							}
							selItem.ZIndex = 0;
							selItem.adjustPos();
							selItem.RemoveFromGroup(NItem.CUR_SEL_ITEM);
						}
					}
				}
			}
		}
	}
}
